#!/bin/python
#-*- coding:utf-8 -*-
# Filename:    main.py
# Revision:    1.0
# Date:        2012-06-14
# Author:      simonzhang
# web:         www.simonzhang.net
# Email:       simon-zzm@163.com
### END INIT INFO
import sys
import re
import tornado.ioloop
import tornado.locale
import tornado.web
import hashlib
from dbmodel import *
from interface import *
from deploylog import * 


class LoginHandler(tornado.web.RequestHandler):
    def get(self):
        _domain, _title = if_get_domain_title()
        _get_real_ip, _get_user_ip = get_clent_ip(self.request)
        _tmp_f = open("key_ip.txt", "rb").read()
        _re_get_ip = re.compile(ur"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
        _login_ip_list = _re_get_ip.findall(_tmp_f)
        for i in _tmp_f:
            if len(i)>7:
                _login_ip_list.append(i[:-1])
        if (len(_login_ip_list) == 0) or \
           (_get_user_ip in _login_ip_list) or \
           (_get_real_ip in _login_ip_list):
            try:
               _get_now_user = self.get_secure_cookie("user").split(",")[0]
            except:
               _get_now_user = "Null"
            _get_user_count = get_user_count( _get_now_user)[0]['c']
            if _get_user_count == 1:
                self.redirect("/index/")
            else:
                self.render("templates/login.html", title = _title)
        else:
            self.redirect("http://www.simonzhang.net")
        
    def post(self):
        _domain, _title = if_get_domain_title()
        try:
            _get_real_ip, _get_user_ip = get_clent_ip(self.request)
            from time import time
            _access_timeout = int(time()) + login_timeout
            name = self.get_argument("login_username")
            passwd = self.get_argument("login_password")
            _passwd = db_get_passwd(name)
            if _passwd is not None:
                if _passwd == hashlib.md5("%s+%s" % (name, passwd)).hexdigest():
                    timeout_days = 7
                    self.set_secure_cookie("user", "%s,%s" % (name, _get_user_ip), \
                                           path="/", expires_days = timeout_days)
                    self.set_secure_cookie("rid", _get_real_ip, path="/", expires_days = timeout_days)
                    self.set_secure_cookie("ttime", str(_access_timeout), path="/", expires_days = timeout_days)
                    self.redirect("/index/")
                else:
                    self.render("templates/login.html", title = _title) 
            else:
               self.render("templates/login.html", title = _title)
        except:
            self.render("templates/login.html", title = _title)
            return

